package com.springboot.last_experiment.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {
    //加上这部分druid的属性配置才能起效
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
        return new DruidDataSource();
    }

    //配置Druid监控
    //测试：localhost:8080/druid
    //1、配置管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        StatViewServlet servlet = new StatViewServlet();
        ServletRegistrationBean bean=new ServletRegistrationBean(servlet,"/druid/*");
        Map<String,String> initParams=new HashMap<>();

        //登录使用的用户名和密码
        initParams.put("loginUsername","Agnes");
        initParams.put("loginPassword","123456");

        bean.setInitParameters(initParams);

        return bean;
    }

    //2、配置监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String,String> initParams=new HashMap<>();
        //设置放行的请求
        initParams.put("exclusions","/druid/*,*.js,*.css");

        bean.setInitParameters(initParams);
        //拦截所有请求
        bean.setUrlPatterns(Arrays.asList("/*"));

        return bean;
    }

}
